//
// Client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include "client.h"
#include "log.h"

using namespace std ;
using boost::asio::ip::tcp;

void makeFavorite (stock::Favorite & favorite)
{
    favorite.set_type (stock::Favorite::QUERY) ;
    favorite.set_name ("tykg") ;
}

void RxMsg (Message & inMsg)
{
    LOGCON.info("ReadSocket Method\n") ;
    stock::Favorite favStock ;

    LOGCON.info("ReadSocket Method - read\n") ;
    LOGCON.infoStream() << inMsg ;
        
    if ( (favStock.ParseFromArray(inMsg.body(),inMsg.body_length())) == true)
    {
        if ( favStock.has_type() )
        {
            LOGCON.infoStream() << "type:" << favStock.type() << "\n" ;
        }
        if ( favStock.has_name() )
        {
            LOGCON.infoStream() << "name:" << favStock.name() << "\n" ;
        }
        if ( favStock.has_market() )
        {
            LOGCON.infoStream() << "market:" << (int)(favStock.market().type()) << "\n" ;
        }
        if ( favStock.has_code() )
        {
            LOGCON.infoStream() << "code:" << favStock.code() << "\n" ;
        }
        if ( favStock.has_description() )
        {
            LOGCON.infoStream() << "description:" << favStock.description() << "\n" ;
        }
    }
}


int main(int argc, char* argv[])
{
    // Verify that the version of the library that we linked against is
    // compatible with the version of the headers we compiled against.
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    try
    {

        boost::asio::io_service io_service;

        tcp::resolver resolver(io_service);
        tcp::resolver::query query("localhost", "20000");
        tcp::resolver::iterator iterator = resolver.resolve(query);

        ClientPtr pClient(new Client(io_service, iterator, RxMsg));
        boost::thread ioThread(boost::bind(&boost::asio::io_service::run, &io_service));

        stock::Favorite fav ;
        Message msg ;
        int count=0;
        while (count++ < 2)
        {
            makeFavorite ( fav ) ;
            if ( fav.ByteSize() > Message::MAX_BODY_LEN ||
                    !fav.SerializeToArray((void *)(msg.body()), (int)(Message::MAX_BODY_LEN) )
               )
            {
                LOGCON.errorStream() << "Failed to serialize." << "\n" ;
                return 0 ;
            }
            msg.body_length(fav.ByteSize()) ;
            msg.encode_header() ;
            pClient->write (msg) ;
            LOGCON.infoStream() << "After write" << "\n" ;
            sleep(5) ;
        }

        pClient->close();
        ioThread.join();
    }
    catch (std::exception& e)
    {
        LOGCON.errorStream() << "Exception: " << e.what() << "\n";
    }

    return 0;
}

